package com.appspot.showup_app.showup.tasks;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;


import com.appspot.showup_app.showup.AppConstants;
import com.appspot.showup_app.showup.ApplicationData;
import com.appspot.showup_app.showup.DatabaseHelper;
import com.appspot.showup_app.showup.DateTimeUtil;
import com.appspot.showup_app.showup.Showup;
import com.appspot.showup_app.showup.ShowupScopes;
import com.appspot.showup_app.showup.model.ShowUpAppointmentMessage;
import com.appspot.showup_app.showup.model.ShowUpBusinessMessage;
import com.appspot.showup_app.showup.model.ShowUpCustomerMessage;
import com.appspot.showup_app.showup.model.ShowUpUpdatesCollection;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;

import java.io.IOException;


public class GetUpdatesTask extends AsyncTask<Void, Void, Boolean> {

    private static final String LOG_TAG = "GetUpdatesTask";
    private static final String TAG = "Showup";
    public static final String LAST_UPDATES_FETCH = "LAST_UPDATES_FETCH";
    private final Context mContext;

    public GetUpdatesTask(Context context) {
        mContext =  context;
    }

    @Override
    protected Boolean doInBackground(Void... unused) {

        if (!AppConstants.checkGooglePlayServicesAvailable((Activity) mContext)) {
            return null;
        }


        GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(mContext.getApplicationContext(), AppConstants.AUDIENCE);
        credential.setSelectedAccountName(ApplicationData.getInstance().emailAccount);
        Showup api = AppConstants.getApiServiceHandle(credential);

        try {
            DatabaseHelper mDbHelper = new DatabaseHelper(mContext);
            SQLiteDatabase db = mDbHelper.getWritableDatabase();
            SharedPreferences settings = mContext.getSharedPreferences(TAG, 0);

            Long timestamp = settings.getLong(LAST_UPDATES_FETCH, 0);
            Long now = DateTimeUtil.getTimestamp();
            ShowUpUpdatesCollection updates = api.updates().list(timestamp).execute();
            settings.edit().putLong(LAST_UPDATES_FETCH, now).apply();

            if (updates.getCustomers() != null) {
                for (ShowUpCustomerMessage customer : updates.getCustomers()) {
                    if (customer.getDeleted())
                        DatabaseHelper.deleteCustomer(db, customer.getId());
                    else
                        DatabaseHelper.addEditCustomer(db, customer);
                }
            }

            if (updates.getAppointments() != null) {
                for (ShowUpAppointmentMessage apt : updates.getAppointments()) {
                    if (apt.getDeleted())
                        DatabaseHelper.deleteAppointment(db, apt.getId());
                    else
                        DatabaseHelper.addAppointment(db, apt);
                }
            }

            ShowUpBusinessMessage businessMessage = updates.getBusinessInfo();
            if (businessMessage != null) {
               DatabaseHelper.updateBusinessInfo(settings, businessMessage);
            }
            return true;

        } catch (Exception e) {
            Log.e(LOG_TAG, "Exception during API call", e);
        }
        return false;
    }
}